<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="~{common/base :: layout(~{::title}, ~{::content}, ~{::style}, ~{::script})}">
<head>
    <title>添加商品 - 优选商城</title>
    <style th:fragment="style">
        .content-wrapper {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .preview-image {
            width: 200px;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
            margin: 10px;
        }
        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        .image-upload-box {
            border: 2px dashed #dee2e6;
            border-radius: 4px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            position: relative;
        }
        .image-upload-box:hover {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .image-upload-box i {
            font-size: 2rem;
            color: #6c757d;
            margin-bottom: 10px;
        }
        .image-upload-box.dragover {
            border-color: #0d6efd;
            background-color: #e7f1ff;
        }
        .preview-image {
            width: 200px;
            height: 200px;
            object-fit: cover;
            border-radius: 4px;
            margin: 10px;
            position: relative;
        }
        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 10px;
        }
        .image-preview-item {
            position: relative;
            display: inline-block;
        }
        .image-preview-item .delete-image {
            position: absolute;
            top: 0;
            right: 0;
            background: rgba(0,0,0,0.5);
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            cursor: pointer;
            display: none;
        }
        .image-preview-item:hover .delete-image {
            display: block;
        }
    </style>
</head>
<body>
    <div th:fragment="content">
        <div class="content-wrapper">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>添加商品</h2>
                <a href="/admin/products" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i> 返回列表
                </a>
            </div>

            <div class="card">
                <div class="card-body">
                    <form id="productForm" class="needs-validation" novalidate>
                        <div class="row">
                            <div class="col-md-8">
                                <!-- 基本信息 -->
                                <div class="mb-4">
                                    <h5 class="card-title mb-3">基本信息</h5>
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label">商品名称 <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" name="name" required>
                                            <div class="invalid-feedback">请输入商品名称</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品副标题</label>
                                            <input type="text" class="form-control" name="subtitle">
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品分类 <span class="text-danger">*</span></label>
                                            <select class="form-select" name="categoryId" required>
                                                <option value="">请选择分类</option>
                                            </select>
                                            <div class="invalid-feedback">请选择商品分类</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品价格 <span class="text-danger">*</span></label>
                                            <div class="input-group">
                                                <span class="input-group-text">¥</span>
                                                <input type="number" class="form-control" name="price" step="0.01" min="0" required>
                                            </div>
                                            <div class="invalid-feedback">请输入有效的商品价格</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">库存数量 <span class="text-danger">*</span></label>
                                            <input type="number" class="form-control" name="stock" min="0" required>
                                            <div class="invalid-feedback">请输入库存数量</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">商品状态</label>
                                            <select class="form-select" name="status">
                                                <option value="1">上架</option>
                                                <option value="0">下架</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <!-- 商品图片 -->
                                <div class="mb-4">
                                    <h5 class="card-title mb-3">商品图片</h5>
                                    <div class="mb-3">
                                        <label class="form-label">主图 <span class="text-danger">*</span></label>
                                        <div class="image-upload-box" id="mainImageUpload">
                                            <i class="bi bi-cloud-upload"></i>
                                            <p class="mb-0">点击或拖拽图片到此处上传</p>
                                            <p class="text-muted small mb-0">支持 jpg、png、gif 格式，大小不超过 2MB</p>
                                            <input type="file" class="d-none" id="mainImage" accept="image/jpeg,image/png,image/gif">
                                        </div>
                                        <div class="image-preview-container">
                                            <div class="image-preview-item" id="mainImagePreviewContainer" style="display: none;">
                                                <img id="mainImagePreview" class="preview-image">
                                                <button type="button" class="delete-image" onclick="deleteMainImage()">
                                                    <i class="bi bi-x"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">子图（可多选）</label>
                                        <div class="image-upload-box" id="subImagesUpload">
                                            <i class="bi bi-images"></i>
                                            <p class="mb-0">点击或拖拽图片到此处上传</p>
                                            <p class="text-muted small mb-0">支持 jpg、png、gif 格式，大小不超过 2MB</p>
                                            <input type="file" class="d-none" id="subImages" accept="image/jpeg,image/png,image/gif" multiple>
                                        </div>
                                        <div class="image-preview-container" id="subImagesPreview"></div>
                                    </div>
                                </div>

                                <!-- 商品详情 -->
                                <div class="mb-4">
                                    <h5 class="card-title mb-3">商品详情</h5>
                                    <textarea class="form-control" name="detail" rows="5" placeholder="请输入商品详细描述..."></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="text-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save"></i> 保存商品
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script th:fragment="script">
        // 加载商品分类
        function loadCategories() {
            $.get('/api/categories', function(res) {
                if (res.code === 0) {
                    const select = $('select[name="categoryId"]');
                    res.data.forEach(category => {
                        select.append(`<option value="${category.id}">${category.name}</option>`);
                    });
                }
            });
        }

        // 图片上传相关函数
        function validateImage(file) {
            const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
            const maxSize = 2 * 1024 * 1024; // 2MB

            if (!validTypes.includes(file.type)) {
                alert('只支持 jpg、png、gif 格式的图片');
                return false;
            }

            if (file.size > maxSize) {
                alert('图片大小不能超过 2MB');
                return false;
            }

            return true;
        }

        function previewImage(file, previewElement) {
            if (!validateImage(file)) {
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                $(previewElement).attr('src', e.target.result);
                $(previewElement).closest('.image-preview-item').show();
            }
            reader.readAsDataURL(file);
        }

        function deleteMainImage() {
            $('#mainImage').val('');
            $('#mainImagePreview').attr('src', '');
            $('#mainImagePreviewContainer').hide();
        }

        function deleteSubImage(index) {
            const files = $('#subImages')[0].files;
            const dt = new DataTransfer();
            
            for (let i = 0; i < files.length; i++) {
                if (i !== index) {
                    dt.items.add(files[i]);
                }
            }
            
            $('#subImages')[0].files = dt.files;
            $(`#subImagePreview_${index}`).remove();
        }

        function previewMultipleImages(files) {
            $('#subImagesPreview').empty();
            
            Array.from(files).forEach((file, index) => {
                if (!validateImage(file)) {
                    return;
                }

                const reader = new FileReader();
                reader.onload = function(e) {
                    const previewItem = $(`
                        <div class="image-preview-item" id="subImagePreview_${index}">
                            <img src="${e.target.result}" class="preview-image">
                            <button type="button" class="delete-image" onclick="deleteSubImage(${index})">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    `);
                    $('#subImagesPreview').append(previewItem);
                }
                reader.readAsDataURL(file);
            });
        }

        // 拖拽上传相关函数
        function handleDragOver(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).addClass('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).removeClass('dragover');

            const files = e.originalEvent.dataTransfer.files;
            if (this.id === 'mainImageUpload') {
                if (files.length > 0) {
                    $('#mainImage')[0].files = files;
                    previewImage(files[0], '#mainImagePreview');
                }
            } else if (this.id === 'subImagesUpload') {
                if (files.length > 0) {
                    const dt = new DataTransfer();
                    Array.from(files).forEach(file => dt.items.add(file));
                    $('#subImages')[0].files = dt.files;
                    previewMultipleImages(files);
                }
            }
        }

        $(document).ready(function() {
            loadCategories();

            // 主图上传
            $('#mainImageUpload')
                .on('dragover', handleDragOver)
                .on('dragleave', handleDragLeave)
                .on('drop', handleDrop)
                .on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $('#mainImage').click();
                });

            $('#mainImage').on('change', function() {
                if (this.files && this.files[0]) {
                    previewImage(this.files[0], '#mainImagePreview');
                }
            });

            // 子图上传
            $('#subImagesUpload')
                .on('dragover', handleDragOver)
                .on('dragleave', handleDragLeave)
                .on('drop', handleDrop)
                .on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $('#subImages').click();
                });

            $('#subImages').on('change', function() {
                if (this.files && this.files.length > 0) {
                    previewMultipleImages(this.files);
                }
            });

            // 防止文件输入框的点击事件冒泡
            $('#mainImage, #subImages').on('click', function(e) {
                e.stopPropagation();
            });

            // 表单提交
            $('#productForm').submit(function(e) {
                e.preventDefault();
                
                // 表单验证
                if (!this.checkValidity()) {
                    e.stopPropagation();
                    $(this).addClass('was-validated');
                    return;
                }

                // 检查主图是否上传
                if (!$('#mainImage')[0].files.length) {
                    alert('请上传商品主图');
                    return;
                }

                // 构建表单数据
                const formData = new FormData();
                const formFields = $(this).serializeArray();
                formFields.forEach(field => {
                    formData.append(field.name, field.value);
                });

                // 添加图片
                const mainImage = $('#mainImage')[0].files[0];
                formData.append('mainImage', mainImage);

                const subImages = $('#subImages')[0].files;
                if (subImages && subImages.length > 0) {
                    Array.from(subImages).forEach(file => {
                        formData.append('subImages', file);
                    });
                }

                // 显示加载状态
                const submitBtn = $(this).find('button[type="submit"]');
                const originalText = submitBtn.html();
                submitBtn.prop('disabled', true).html('<i class="bi bi-hourglass-split"></i> 保存中...');

                // 提交表单
                $.ajax({
                    url: '/admin/products/save',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.code === 0) {
                            alert('保存成功');
                            location.href = '/admin/products';
                        } else {
                            alert(res.msg || '保存失败');
                        }
                    },
                    error: function(xhr) {
                        console.error('保存失败:', xhr);
                        alert('保存失败，请重试');
                    },
                    complete: function() {
                        submitBtn.prop('disabled', false).html(originalText);
                    }
                });
            });
        });
    </script>
</body>
</html> 